#! /usr/bin/env/ python
# -*- coding: utf-8 -*-

# (C) 2010 by Rocco Orlando Rossi
# Released under the GPL 3 Free Software License

import sys
import gobject
import gtk
import re
import urllib2
from multiprocessing import Process, Queue
from Queue import Empty
from xmlrpclib import ServerProxy
from numbers import Number

def convert(source, target, oqueue):
    url = 'http://foxrate.org/rpc/'
    try:
        proxy = ServerProxy(url)
        result = proxy.foxrate.currencyConvert(source, target, 1.0)
    except:
        result = None
    oqueue.put(result)
    oqueue.close()

def set_model_from_list (cb, items):        
    model = gtk.ListStore(str)
    for i in items:
        model.append([i])
    cb.set_model(model)
    if type(cb) == gtk.ComboBoxEntry:
        cb.set_text_column(0)
    elif type(cb) == gtk.ComboBox:
        cell = gtk.CellRendererText()
        cb.pack_start(cell, True)
        cb.add_attribute(cell, 'text', 0)

class AboutDialog(object):
    def __init__(self):
        self.builder = gtk.Builder()
        self.builder.add_from_file('gui/about.glade')
        self.builder.connect_signals(self)
        info = self.builder.get_object('aboutdialog1')
        info.show()
    
    def on_aboutdialog1_close(self, widget, *args):
        info = self.builder.get_object('aboutdialog1')
        info.destroy() 
        
        
class PyCurrency(object):
    def __init__(self):
        f = open('data/codes.txt')
        self.CURRENCIES = sorted(map(lambda s: s.strip('\n'), f.readlines()))
        f.close()
        self.builder = gtk.Builder()
        self.builder.add_from_file('gui/pycurrency.glade')
        self.builder.connect_signals(self)
        self.pb = self.builder.get_object('progressbar1')
        self.pb.set_fraction(0.0)
        combo = self.builder.get_object('combobox1')
        combo.set_wrap_width(10)
        set_model_from_list(combo, self.CURRENCIES)
        combo.set_active(self.CURRENCIES.index('EUR'))
        combo = self.builder.get_object('combobox2')
        combo.set_wrap_width(10)
        set_model_from_list(combo, self.CURRENCIES)
        combo.set_active(self.CURRENCIES.index('USD'))
        window = self.builder.get_object('window1')
        window.show()
    
    def timeout_callback(self, process, oqueue, money):
        self.pb.pulse()
        try:
            result = oqueue.get_nowait()
        except Empty:
            return True
        else:
            process.join()
            if result:
                amount = result['amount']
                flerror = result['flerror']
                message = result['message']
                if not flerror and isinstance(amount, Number):
                    conv = str(amount*money)
                    self.builder.get_object('entry2').set_text(conv)
                    self.pb.set_text('Operazione eseguita')
                else:
                    conv = 'Errore: {0}'.format('Valore non valido')
                    self.builder.get_object('entry2').set_text('')
                    self.pb.set_text(conv)
            else:
                conv = 'Errore: Non pervenuto'
                self.pb.set_text(conv)
            self.pb.set_fraction(0.0)
            return False
    
    def on_button1_clicked(self, widget, *args):
        self.pb.set_text('Connessione ...')
        try:
            money = float(self.builder.get_object('entry1').get_text())
        except (TypeError, ValueError):
            result = '0.0'
        else:
            source = self.builder.get_object('combobox1').get_active_text()
            target = self.builder.get_object('combobox2').get_active_text()
            if source != target:   
                oqueue = Queue()
                process = Process(target=convert, args=(source, target, oqueue))
                process.start()
                source_id = gobject.timeout_add(50, self.timeout_callback, process, oqueue, money)
                return
            else:
                result = '1.0'
        self.builder.get_object('entry2').set_text(result)
     
    def on_button2_clicked(self, widget, *args):
        about_dialog = AboutDialog()
        
    def on_button3_clicked(self, widget, *args):
        window = self.builder.get_object('window1')
        window.destroy()
        gtk.main_quit()
        
    def on_button4_clicked(self, widget, *args):
        cmb1 = self.builder.get_object('combobox1')
        cmb2 = self.builder.get_object('combobox2')
        source = cmb1.get_active_text()
        target = cmb2.get_active_text()
        cmb1.set_active(self.CURRENCIES.index(target))
        cmb2.set_active(self.CURRENCIES.index(source))
        
def main():
    app = PyCurrency()
    gtk.main()
    
if __name__ == '__main__':
    main()
